﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using log4net.Core;
using Quartz;
using ServiceContainer.Commom;
using YouWei.Infrastructure;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Enums;
using YouWei.Infrastructure.Service;
using YouWei.Utility;
using YouWei.Utility.Logging;

namespace ServiceContainer.Jobs
{


    /// <summary>
    /// 短信发送服务，根据品牌、车型从短信池中筛选出相应的数据，并将这些数据插入到短信中间件对应的存储位置
    /// </summary>
    [DisallowConcurrentExecution]
    public class SmsSendJob : IJob
    {
       
        ///// <summary>
        ///// 作业ID
        ///// </summary>
        //private int m_jobID = (int) JobEnum.SendSmsMsgJob;

        private string m_lastExcuteDate= DateTime.Now.ToString("yyyyMMdd");

        /// <summary>
        ///  任务队列
        /// </summary>
        //private List<SmsTask>  m_listTask=new List<SmsTask>();

       private ConcurrentDictionary<int, SmsTask> m_AllTasks= new ConcurrentDictionary<int, SmsTask>();

        private ConcurrentDictionary<int,TaskWrapper> m_dicTask=new ConcurrentDictionary<int, TaskWrapper>();

        private ConcurrentDictionary<int, TaskWrapper> m_dicTaskTimes = new ConcurrentDictionary<int, TaskWrapper>();

        private int m_TaskCount = 0;
        private int m_TaskTimeCount = 0;
       
        public void Execute(IJobExecutionContext context)
        {
          
            try
            {
                //后台任务监控方法
                Task.Factory.StartNew(MonitorAllTasks);
                StartWork(context);
            }
            catch (Exception ex)
            {
                Log4netLog.Error(101,ex);
            }
           
        }

        private void StartWork(IJobExecutionContext context)
        {
            SmsTaskService svTask = new SmsTaskService();

            DoTodayWork(context);
            while (true)
            {
                #region 比较日期，当日期变化时重新获取任务执行
                var nowDate = DateTime.Now.ToString("yyyyMMdd");
                if (nowDate != m_lastExcuteDate)
                {
                    m_lastExcuteDate = nowDate;
                    if (StopAllTasks())
                    {
                        string szInfo = $"日期变更，已经移除所有任务，当前程序共有{m_dicTask.Count}个任务，{m_dicTaskTimes.Count}个任务周期 在运行！！！";
                        Log4netLog.Info(szInfo);

                        DoTodayWork(context);
                    }
                    else
                    {
                        Log4netLog.Info("停止后台线程超时失败！");
                    }

                }
                #endregion

                #region 监测有无新任务被添加
                var listNew = svTask.GetAllTasks(DateTime.Now);
                var listNewAdded = listNew.Where(item => m_AllTasks.All(m => m.Key != item.TaskID)).ToList();
                if (listNewAdded.Any())
                {
                    listNewAdded.ForEach(m =>
                    {
                       m_AllTasks.TryAdd(m.TaskID, m);
                    });
                    DoTasks(listNewAdded);
                    var listName = listNewAdded.Select(m => m.TaskName);
                    if (listName.Any())
                    {
                        var names = string.Join(",", listName);
                        Log4netLog.Info($"新增了{listNewAdded.Count}个任务，分别为：{names}");
                    }
                }
                #endregion


                Thread.Sleep(1*60*1000);//每隔1分钟检测一次有无新增任务
            }
        }

        private void DoTodayWork(IJobExecutionContext context)
        {
            SmsTaskService svTask = new SmsTaskService();

            //获取启动日期当天任务队列
            var nowDateTasks = svTask.GetAllTasks(DateTime.Now);
            nowDateTasks.ForEach(m =>
            {
                if (m_AllTasks.ContainsKey(m.TaskID))
                {
                    m_AllTasks.TryAdd(m.TaskID, m);
                }
            });

            //第一次执行
            DoTasks(nowDateTasks);
        }

        private void DoTasks(List<SmsTask> listTask)
        {
            
            //执行当天任务
            foreach (var task in listTask)
            {
               
                
                //如果任务已存在，则不添加
                if (m_dicTask.ContainsKey(task.TaskID))
                {
                    continue;
                }

                var source = new CancellationTokenSource();
                var oWrapper=new TaskWrapper();

                var newTask = new Task(() =>
                {
                    DoTask(task);
                }, source.Token);
                oWrapper = new TaskWrapper()
                {
                    Model =newTask,
                    Token = source
                };
                oWrapper.Token.Token.Register(() =>
                {

                    bool bRemoved = m_dicTask.TryRemove(task.TaskID, out oWrapper);
                    if (bRemoved)
                    {
                        //m_listTask.Remove(task);
                        var removeTask=new SmsTask();
                        var bRemoveTask=m_AllTasks.TryRemove(task.TaskID, out removeTask);
                        if (bRemoveTask)
                        {
                            Log4netLog.Info($"移除任务{task.TaskID}成功,同时从任务列表中删除了任务（ID：{task.TaskID},名称：{task.TaskName}）");
                            m_TaskCount--;
                        }
                        else
                        {
                            Log4netLog.Info($"移除任务{task.TaskID}失败");
                        }
                        
                    }
                    else
                    {
                        Log4netLog.Info($"移除任务{task.TaskID}失败了");
                    }
                });
                bool bIsNewTask=m_dicTask.TryAdd(task.TaskID, oWrapper);
                if (bIsNewTask)
                {
                    newTask.Start();
                    m_TaskCount++;
                }
            }
        }

        private void DoTask(SmsTask task)
        {

            var taskID = task.TaskID;
            
            while (true)
            {
                SmsTaskService svTask = new SmsTaskService();
                var listTaskTime = svTask.GetAllTaskTimes(task);
                var listBlackDay = svTask.GetAllTaskBlackDay(taskID);
                foreach (var taskTime in listTaskTime)
                {
                   
                    //黑名单日期，不执行
                    if (CheckTodayIsInBlackDay(listBlackDay))
                    {
                       break;
                    }
                    //排除过期任务周期
                    if (CheckTaskTimeExpired(task,DateTime.Now, taskTime))
                    {
                        if (m_dicTaskTimes.ContainsKey(taskTime.ID))
                        {
                            m_dicTaskTimes[taskTime.ID].Token.Cancel();
                        }
                        continue;
                    }

                    //如果已有执行的任务周期线程，则不再重复创建
                    if (m_dicTaskTimes.ContainsKey(taskTime.ID))
                    {
                        continue;
                    }
                    

                    var source = new CancellationTokenSource();
                    var newTaskTime = new Task(() =>
                    {
                        DoTaskTime(task, taskTime);
                    }, source.Token);
                    var oWrapper = new TaskWrapper()
                    {
                        Model = newTaskTime,
                        Token = source
                    };
                    oWrapper.Token.Token.Register(() =>
                    {
                        
                        bool bRemoved=m_dicTaskTimes.TryRemove(taskTime.ID, out oWrapper);
                        if (bRemoved)
                        {
                            Log4netLog.Info($"移除任务周期{taskTime.ID}成功");
                            m_TaskTimeCount--;

                        }
                        else
                        {
                            Log4netLog.Info($"移除任务周期{taskTime.ID}失败了");
                        }
                    });
                    bool bIsNewTask=m_dicTaskTimes.TryAdd(taskTime.ID, oWrapper);
                    if (bIsNewTask)
                    {
                        newTaskTime.Start();
                        m_TaskTimeCount++;
                    }
                }
                Thread.Sleep(60*1000);//每隔1分钟检测一次有无新增任务周期
            }
            
        }

        private void DoTaskTime(SmsTask task,SmsTaskTime taskTime)
        {
           
            if (taskTime.TimeType == 1)
            {
                if (!CheckTaskTimeExpired(task,DateTime.Now, taskTime))
                {
                    DoTaskTime1(task, taskTime);
                }
                else
                {
                    var outTask = new TaskWrapper();
                    if (m_dicTaskTimes.TryGetValue(taskTime.ID, out outTask))
                    {
                        outTask.Token.Cancel(); ;
                    }
                }
            }

            //其他类型后续补充。。
        }

        private bool CheckTaskTimeExpired(SmsTask task,DateTime dtNow, SmsTaskTime taskTime)
        {
            bool bReturn = false;
            if (taskTime.TimeType == 1)
            {
                if (task.StartDate <= dtNow && dtNow < task.EndDate && dtNow.Hour >= taskTime.StartTime && dtNow.Hour < taskTime.EndTime)
                {

                }
                else
                {
                    bReturn = true;
                }
            }
            return bReturn;

        }

        private void DoTaskTime1(SmsTask task, SmsTaskTime taskTime)
        {
           
            var svCard = new SmsCardService();
            var svMessage = new SmsMessagePoolService();
            var svTemplate=new SmsTemplateService();


            var nNeedSendCount = taskTime.SendCount-taskTime.RealSendCount;

            //设置一组随机数
            int[] arrInterval = new int[] { 1,2,3,4,5,6,7,8,9};
            var random = new Random();
            int nSleepTime = 0;

            //已发送短信个数
            var nAlreadySendCount = 0;
            var nFirstGroupCount = 0;
          
            while (nNeedSendCount > 0 && !CheckTaskTimeExpired(task,DateTime.Now,taskTime))
            {
                var dtStartTime = DateTime.Now;
                var dtLastOneHourTime = dtStartTime.AddHours(-1);
                //var listAvailableCard = svCard.GetAvaliableCards(dtStartTime, dtEndTime);

                var listAvailableCard = svCard.GetAvaliableCards(task.TaskID, dtLastOneHourTime,dtStartTime);


                //按品牌、车型获取短信模板
                //var listTemplate = svTemplate.GetAvalilabeTemplates(task.CarBrand, task.CarSerial);

                //获取可用的短信模板
                var listTemplate = svTemplate.GetAllAvalilabeTemplates();

                //最少发送次数为卡池中可用卡的数目
                var nGroupSendCount = listAvailableCard.Count;
                if (nGroupSendCount == 0)
                {
                    Log4netLog.Info($"任务{task.TaskName}，ID({task.TaskID})，暂时没有用用卡片，处于等待状态");
                    Thread.Sleep(60*1000);
                    continue;
                }

                var nGroupCount = EConvert.ToInt(Decimal.Ceiling(EConvert.ToDecimal(nNeedSendCount) / EConvert.ToDecimal(nGroupSendCount)));

                if (nFirstGroupCount == 0)
                {
                    nFirstGroupCount = nGroupSendCount;
                }
                //计算总共需要发送时间
                var dtTaskEndTime = new DateTime(dtStartTime.Year, dtStartTime.Month, dtStartTime.Day, taskTime.EndTime, 0, 0);
                var dtTaskStartTime = dtStartTime;
                var nTotalMillSeconds = (dtTaskEndTime - dtTaskStartTime).TotalMilliseconds;
                //var nTotalMillSeconds = 60 * 10 * 1000-nSleepTime;


                //计算多长时间发一组短信，单位为：ms
                var nAverangeTime = EConvert.ToInt(Decimal.Ceiling(EConvert.ToDecimal(nTotalMillSeconds) / EConvert.ToDecimal(nGroupCount)));
                if (nAverangeTime <= 0)
                {
                    break;
                }
                if (nGroupCount == 1 && nNeedSendCount < nGroupSendCount)
                {
                    nGroupSendCount = nNeedSendCount%nGroupSendCount;
                }
                //获取要发送短信的电话号码
                var listGroupMsg = svMessage.GetGroupMsgs(task.CarBrand,task.CarSerial,nGroupSendCount);
                //当没有数据时结束任务周期
                if (!listGroupMsg.Any())
                {
                    break;
                }

                var nRandom = random.Next(0, arrInterval.Length - 1);
                nSleepTime = nAverangeTime - (arrInterval[nRandom] * 1000);
                //一组发送频率至少45秒以上 
                if (nSleepTime < 45000)
                {
                    nSleepTime = 40000;
                }
                //发送一组短信
                SendGroupSmsMsg(task,listGroupMsg, listAvailableCard, listTemplate,nSleepTime,taskTime);
                //更新实际发送数量
                UpdateRealSendCount(taskTime,listGroupMsg.Count);

                nNeedSendCount = nNeedSendCount - nGroupSendCount;

                nAlreadySendCount += nGroupSendCount;


                //首组发送测试短信或者发送10组之后也发送测试短信掌握短信发送状态是否异常
                //var bFirstSend = (nGroupSendCount == nAlreadySendCount);
                //if ((nAlreadySendCount % (nFirstGroupCount * 30)) == 0)//bFirstSend || 
                //{
                //    SendTestMsg(task,listAvailableCard, listTemplate);
                //}
                ////最后一组发送短信发送任务结束通知短信
                //else if (nNeedSendCount == 0)
                //{
                //    SendEndJobTestMsg(listAvailableCard);
                //}

                //if (nNeedSendCount == 0)
                //{
                //    SendEndJobTestMsg(listAvailableCard);
                //}

            }
            if (m_dicTaskTimes.ContainsKey(taskTime.ID))
            {
                m_dicTaskTimes[taskTime.ID].Token.Cancel();
            }
           

            
        }

        #region 发送一组短信
        private void SendGroupSmsMsg(SmsTask task, List<SmsMessagePool> listMsg, List<SmsCard> listCard, List<SmsTemplate> listTpl, int sendTotalMillSeconds, SmsTaskTime taskTime)
        {
            var nextGroupSendTime = DateTime.Now.AddMilliseconds(sendTotalMillSeconds);
            var svSmsTaskTimeStatstics = new SmsTaskTimeStatsticsService();
            var random = new Random();
            var arrInterval = new int[] { 1,2,3, };//单位，秒
                                                                                      //发送一条短信平均时间，单位 ms
            var nAverangeTime = EConvert.ToInt(Decimal.Ceiling(EConvert.ToDecimal(sendTotalMillSeconds) / EConvert.ToDecimal(listMsg.Count)));

            for (var i = 0; i < listMsg.Count; i++)
            {
                var nItemIndex = random.Next(0, listTpl.Count);
                //获取随机短信模板
                var tpl = listTpl[nItemIndex];

                var nRandom = random.Next(0, arrInterval.Length - 1);
                var nSleepTime = nAverangeTime - (arrInterval[nRandom] * 1000);

                var oCard = listCard[i];
                //if (taskTime.CardID > 0)
                //{
                //    oCard = listCard.FirstOrDefault(m => m.CardID == taskTime.CardID) ?? listCard[i];
                //}

                //发送一条短信
                if (AppAlarmHelper.SwitchTriiger)
                {
                    SendSingleMsg(task, taskTime, listMsg[i], oCard, tpl);
                }
              

                DateTime dtNow = DateTime.Now;
                var nextSendTime = dtNow.AddMilliseconds(nSleepTime);
                if (i == listMsg.Count - 1)//最后一条间隔设为下一组发送短信的发送时间
                {
                    nextSendTime = nextGroupSendTime;
                    nSleepTime = EConvert.ToInt((nextGroupSendTime - DateTime.Now).TotalMilliseconds);
                }
                var oTaskTimeStatistics = new SmsTaskTimeStatstics()
                {
                    TaskTimeID = taskTime.ID,
                    RealSendCount = 1,
                    NextSendTime = nextSendTime,
                    CreatedTime = dtNow,
                    UpdatedTime = dtNow,
                };
                svSmsTaskTimeStatstics.Insert(oTaskTimeStatistics);

                if (nSleepTime <= 0)
                {
                    nSleepTime = 450000;
                }
                Thread.Sleep(nSleepTime);
            }
        }


        #endregion
        

        #region 发送单条短信方法
        /// <summary>
        /// 发送短信方法总入口，具体调用真实方法还是模拟方法，请参照配置文件
        /// </summary>
        private void SendSingleMsg(SmsTask task, SmsTaskTime taskTime, SmsMessagePool msg, SmsCard card, SmsTemplate tpl)
        {
            ;
            if (ServiceContainerAppsetings.IsTestMode)
            {
                SendMockSingleMsg(task, taskTime, msg, card, tpl);
            }
            else
            {
                SendRealSingleMsg(task, taskTime, msg, card, tpl);
            }
        }


        /// <summary>
        /// 真实发送短信方法
        /// </summary>
        /// <param name="task"></param>
        /// <param name="taskTime"></param>
        /// <param name="msg"></param>
        /// <param name="card"></param>
        /// <param name="tpl"></param>
        private void SendRealSingleMsg(SmsTask task, SmsTaskTime taskTime, SmsMessagePool msg, SmsCard card, SmsTemplate tpl)
        {
            //插入mysql数据，返回sendID,再更新msg的状态
            var svSmsSend = new sms_sendService();
            var svSmsMsgPool = new SmsMessagePoolService();

            var smsContent = GetSendContent(task, tpl);
            //var smsContent = "hello acheng";
            var oSendMsg = new sms_send();
            oSendMsg.PortNum = -1;
            oSendMsg.smsNumber = msg.ReceiveMobile;
            oSendMsg.smsSubject = string.Empty;
            //oSendMsg.smsContent = msg.Content;
            oSendMsg.smsContent = smsContent;

            oSendMsg.smsType = 0;
            oSendMsg.PhoNum = card.OwnerMobile;
            oSendMsg.smsState = 0;

            int nSendID = 0;

            object o = svSmsSend.Insert(oSendMsg);
            if (o != null)
            {
                nSendID = EConvert.ToInt(o);

                msg.SendDate = DateTime.Now;
                msg.SmsCatSendID = nSendID;
                msg.SmsTplID = tpl.TemplateID;
                msg.Content = smsContent;

                msg.IsJoinSendQueue = 1;
                svSmsMsgPool.Update(msg);
            }
            else
            {
                Log4netLog.Error("插入短信猫数据失败，插入数据为：" + msg.ToJSON());
            }
        }

        /// <summary>
        /// 模拟发送短信方法
        /// </summary>
        /// <param name="task"></param>
        /// <param name="taskTime"></param>
        /// <param name="msg"></param>
        /// <param name="card"></param>
        /// <param name="tpl"></param>
        private void SendMockSingleMsg(SmsTask task, SmsTaskTime taskTime, SmsMessagePool msg, SmsCard card, SmsTemplate tpl)
        {
            var svMockTest = new SmsMockTestService();
            var smsContent = GetSendContent(task, tpl);
            //var smsContent = "hello acheng";
            var oSendMsg = new SmsMockTest();
            oSendMsg.DeviceID = 0;
            oSendMsg.SendMobile = card.OwnerMobile;
            oSendMsg.ReceiveMobile = msg.ReceiveMobile;
            oSendMsg.SendContent = smsContent;
            oSendMsg.TaskID = task.TaskID;
            oSendMsg.TaskTimeID = taskTime.ID;
            oSendMsg.SendCardID = card.CardID;
            oSendMsg.CarBrand = tpl.CarBrad;
            oSendMsg.CarSerial = tpl.CarSerial;
            oSendMsg.CreatedTime = DateTime.Now;
            //插入模拟短信
            object o = svMockTest.Insert(oSendMsg);

        }

        #endregion

        #region 帮助方法
        private void UpdateRealSendCount(SmsTaskTime taskTime, int groupCount)
        {
            var svSmsTaskTime = new SmsTaskTimeService();
            taskTime.RealSendCount += groupCount;
            svSmsTaskTime.Update(taskTime);
        }
        private bool CheckTaskIsExpired(SmsTask task)
        {
            bool bReturn = false;
            var dtNow = DateTime.Now;
            if (dtNow > task.EndDate)
            {
                bReturn = true;
            }
            return bReturn;
        }
        private string GetSendContent(SmsTask task, SmsTemplate tpl)
        {
            var svPlaceHolder = new SmsPlaceHolderService();
            string szReturn = string.Empty;
            var tplContent = tpl.SmsContent;
            string[] arrPlaceHolder = new string[tpl.PlaceHolderLength];
            for (var i = 0; i < tpl.PlaceHolderLength; i++)
            {
                //var szPlaceHolderText = (svPlaceHolder.GetRandomPlaceHolder(tpl.TemplateID, tpl.CarBrad, tpl.CarSerial, i + 1) ?? new SmsPlaceHolder()).PlaceHolderText;


                var szPlaceHolderText = (svPlaceHolder.GetTemplatePlaceHolder(tpl.TemplateID, i + 1) ?? new SmsPlaceHolder()).PlaceHolderText;

                arrPlaceHolder[i] = szPlaceHolderText;
            }
            szReturn = string.Format(tplContent, arrPlaceHolder);
            szReturn = szReturn
                .Replace("【品牌车系】", task.MsgCarBrandName)
                .Replace("【群主名称】", task.GroupOwnerName)
                .Replace("【微信号码】", task.GroupOwnerWxNumber)
            ;
            return szReturn;
        }
        

        /// <summary>
        /// 发送测试短信
        /// </summary>
        /// <param name="task"></param>
        /// <param name="listCard"></param>
        /// <param name="listTpl"></param>
        private void SendTestMsg(SmsTask task, List<SmsCard> listCard, List<SmsTemplate> listTpl)
        {
            //插入mysql数据，返回sendID,再更新msg的状态
            var svSmsSend = new sms_sendService();
            var svSmsTestPerson = new SmsTestPersonService();
            var svSmsMsgPool = new SmsMessagePoolService();

            var listTestPerson = svSmsTestPerson.QueryList(m => m.IsDeleted == 0);
            foreach (var card in listCard)
            {

                foreach (var person in listTestPerson)
                {

                    var random = new Random();
                    //var cardIndex = random.Next(0, listCard.Count - 1);
                    //var oCard = listCard[cardIndex];
                    var tplIndex = random.Next(0, listTpl.Count - 1);
                    var tpl = listTpl[tplIndex];
                    var smsContent = GetSendContent(task, tpl);

                    var oSendMsg = new sms_send();

                    oSendMsg.PortNum = -1;
                    oSendMsg.smsNumber = person.Mobile;
                    oSendMsg.smsSubject = string.Empty;
                    //oSendMsg.smsContent = msg.Content;
                    oSendMsg.smsContent = smsContent;

                    oSendMsg.smsType = 0;
                    oSendMsg.PhoNum = card.OwnerMobile;
                    oSendMsg.smsState = 0;

                    object o = svSmsSend.Insert(oSendMsg);

                    //if (o != null)
                    //{
                    //    var msg=new SmsMessagePool();
                    //    var nSendID = EConvert.ToInt(o);
                    //    msg.Content = smsContent;
                    //    msg.ReceiveMobile = person.Mobile;

                    //    msg.SendStatus = 0;
                    //    msg.SendDate = DateTime.Now;
                    //    msg.SmsCatSendID = nSendID;
                    //    msg.SmsTplID = tpl.TemplateID;
                    //    msg.CarBrand = tpl.CarBrad;
                    //    msg.CarSerial = tpl.CarSerial;
                    //    msg.IsJoinSendQueue = 1;
                    //    svSmsMsgPool.Insert(msg);
                    //}
                    //else
                    //{
                    //    Log4netLog.Error("插入短信猫数据失败，插入数据为：" + oSendMsg.ToJSON());
                    //}

                }
                Thread.Sleep(15000);
            }



        }

        private void SendEndJobTestMsg(List<SmsCard> listCard)
        {
            //插入mysql数据，返回sendID,再更新msg的状态
            var svSmsSend = new sms_sendService();
            var svSmsTestPerson = new SmsTestPersonService();

            var listTestPerson = svSmsTestPerson.QueryList(m => m.IsDeleted == 0);
            var szTestMsgTpl = "Hello {0},I'm ok now, baby!";

            foreach (var card in listCard)
            {
                foreach (var person in listTestPerson)
                {
                    var oSendMsg = new sms_send();
                    oSendMsg.PortNum = -1;
                    oSendMsg.smsNumber = person.Mobile;
                    oSendMsg.smsSubject = string.Empty;
                    oSendMsg.smsContent = string.Format(szTestMsgTpl, person.PersonName + DateTime.Now.ToString("yyyyMMddHHmmss"));
                    oSendMsg.smsType = 0;
                    oSendMsg.PhoNum = card.OwnerMobile;
                    oSendMsg.smsState = 0;
                    object o = svSmsSend.Insert(oSendMsg);
                }
                Thread.Sleep(15000);
            }


        }

        /// <summary>
        /// 检查当前日期是否为对应任务黑名单日期
        /// </summary>
        /// <param name="listBlackDays"></param>
        /// <returns></returns>
        private bool CheckTodayIsInBlackDay(List<SmsBlackDay> listBlackDays)
        {
            bool bReturn = false;

            var dtNow = DateTime.Now;
            var nNowWeekDay = dtNow.GetWeekNameOfDayInt();
            var nNowDateInt = EConvert.ToInt(dtNow.ToString("yyyyMMdd"));
            foreach (var m in listBlackDays)
            {
                if (m.DateType == 1)
                {
                    if (nNowWeekDay == m.DateValue)
                    {
                        bReturn = true;
                        break;
                    }
                }
                else if (m.DateType == 2)
                {
                    if (nNowDateInt == m.DateValue)
                    {
                        bReturn = true;
                        break;
                    }
                }
            }
            return bReturn;
        }
        #endregion

        /// <summary>
        /// 获取当前所有的后台作业信息
        /// </summary>
        public void MonitorAllTasks()
        {
           
            while (true)
            {
                if (DateTime.Now.Hour >= 0 && DateTime.Now.Hour <= 23)
                {
                    string szInfo = $"当前程序共有{m_TaskCount}个任务，{m_TaskTimeCount}个任务周期 在运行！！！";
                    if (DateTime.Now.Minute % 5 == 0 && DateTime.Now.Second == 0)// 
                    {
                        Log4netLog.Info(szInfo);
                    }
                    else if (DateTime.Now.Minute%25==0 && DateTime.Now.Second==0  && DateTime.Now.Hour >= 8 && DateTime.Now.Hour <= 22)
                    {
                   
                        ChannelShortMsgHelper.SendProductMsg("13436300382", szInfo);
                    }
                }
                Thread.Sleep(1000);//每20执行一次
            }
          
        }
        /// <summary>
        /// 停止所有任务
        /// </summary>
        private bool StopAllTasks()
        {
            bool bReturn = false;
            Log4netLog.Info("正在停止所有任务线程，请等待..");
            
            var task=new Task(() =>
            {
                //停止所有任务周期线程的执行
                foreach (var item in m_dicTaskTimes)
                {
                    item.Value.Token.Cancel();
                }
                //停止所有任务线程的执行
                foreach (var item in m_dicTask)
                {
                    item.Value.Token.Cancel();
                }
                while (m_TaskCount > 0 && m_TaskTimeCount > 0)
                {
                    ;
                }
                bReturn = true;
            });
            task.Start();
            if (task.Wait(10*60*1000))
            {
                Log4netLog.Info("所有任务线程已停止");
            }
            else
            {
                Log4netLog.Info("停止所有任务线程超时失败");
            }
         
            return bReturn;
        }


    }

    public class TaskWrapper
    {
        public Task Model { get; set; }
        public CancellationTokenSource Token { get; set; }
    }


    

}
